package com.sk.weichat.ui.contacts;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;

import com.sk.weichat.AppConstant;
import com.sk.weichat.R;
import com.sk.weichat.adapter.BlackAdapter;
import com.sk.weichat.bean.AttentionUser;
import com.sk.weichat.bean.Friend;
import com.sk.weichat.bean.message.ChatMessage;
import com.sk.weichat.bean.message.NewFriendMessage;
import com.sk.weichat.bean.message.XmppMessage;
import com.sk.weichat.broadcast.CardcastUiUpdateUtil;
import com.sk.weichat.broadcast.MsgBroadcast;
import com.sk.weichat.db.InternationalizationHelper;
import com.sk.weichat.db.dao.FriendDao;
import com.sk.weichat.db.dao.NewFriendDao;
import com.sk.weichat.helper.DialogHelper;
import com.sk.weichat.ui.base.BaseActivity;
import com.sk.weichat.ui.me.PersonalCenterActivity;
import com.sk.weichat.util.TimeUtils;
import com.sk.weichat.util.ToastUtil;
import com.sk.weichat.xmpp.ListenerManager;
import com.xuan.xuanhttplibrary.okhttp.HttpUtils;
import com.xuan.xuanhttplibrary.okhttp.callback.BaseCallback;
import com.xuan.xuanhttplibrary.okhttp.callback.ListCallback;
import com.xuan.xuanhttplibrary.okhttp.result.ArrayResult;
import com.xuan.xuanhttplibrary.okhttp.result.ObjectResult;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import okhttp3.Call;

/**
 * 黑名单列表
 */
public class BlackActivity extends BaseActivity {
    private RecyclerView mPullToRefreshListView;
    private BlackAdapter mAdapter;
    private List<AttentionUser> mSortFriends;
    private String mLoginUserId;
    private BroadcastReceiver mUpdateReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(CardcastUiUpdateUtil.ACTION_UPDATE_UI)) {
                getBlackList();
//                mAdapter.setData(mSortFriends);
            }
        }
    };

    public BlackActivity() {
        mSortFriends = new ArrayList<>();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_black);
        mLoginUserId = coreManager.getSelf().getUserId();
        initActionBar();
        initView();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(mUpdateReceiver);
    }

    private void initActionBar() {
        getSupportActionBar().hide();
        findViewById(R.id.iv_title_left).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        TextView mTvTitle = (TextView) findViewById(R.id.tv_title_center);
        mTvTitle.setText(R.string.black_list);
    }

    private void initView() {
        mPullToRefreshListView =  findViewById(R.id.pull_refresh_list);
        mPullToRefreshListView.setLayoutManager(new LinearLayoutManager(this));
     /*   mPullToRefreshListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                AttentionUser attentionUser = mSortFriends.get(position);
                if (attentionUser != null) {
                    Intent intent = new Intent(BlackActivity.this, PersonalCenterActivity.class);
                    intent.putExtra(AppConstant.EXTRA_USER_ID, attentionUser.getToUserId());
                    startActivity(intent);
                }
            }
        });*/

        mAdapter = new BlackAdapter( mSortFriends, new BlackAdapter.removeBlackFriendListener() {
            @Override
            public void removeBlackFriend(int position) {
                removeBlacklist(mSortFriends.get(position));
            }
        });
        mPullToRefreshListView.setAdapter(mAdapter);
        getBlackList();
        registerReceiver(mUpdateReceiver, CardcastUiUpdateUtil.getUpdateActionFilter());
    }

    /**
     * 获取黑名单列表
     */
    private void getBlackList() {
        DialogHelper.showDefaulteMessageProgressDialog(this);
        HashMap<String, String> params = new HashMap<>();
        params.put("access_token", coreManager.getSelfStatus().accessToken);

        HttpUtils.get().url(coreManager.getConfig().FRIENDS_BLACK_LIST)
                .params(params)
                .build()
                .execute(new ListCallback<AttentionUser>(AttentionUser.class) {
                    @Override
                    public void onResponse(ArrayResult<AttentionUser> result) {
                        DialogHelper.dismissProgressDialog();
                        if (result.getResultCode() == 1) {
                            List<AttentionUser> attentionUsers = result.getData();
                            if (attentionUsers != null && attentionUsers.size() > 0) {
                                findViewById(R.id.ll_black_empty).setVisibility(View.GONE);
                                findViewById(R.id.fl_black_content).setVisibility(View.VISIBLE);
                                if (mSortFriends.size()>0){
                                    mSortFriends.clear();
                                }
//                                for (int i = 0; i<attentionUsers.size(); i++) {
//                                    mSortFriends.add(attentionUsers.get(i));
//                                }
                                mSortFriends.addAll(attentionUsers);
                                mAdapter.notifyDataSetChanged();
                            } else {
                                findViewById(R.id.ll_black_empty).setVisibility(View.VISIBLE);
                                findViewById(R.id.fl_black_content).setVisibility(View.GONE);
                            }
                        }
                    }

                    @Override
                    public void onError(Call call, Exception e) {
                        DialogHelper.dismissProgressDialog();
                        ToastUtil.showErrorNet(mContext);
                    }
                });
    }

    /**
     * 移除黑名单
     * */
    private void removeBlacklist(AttentionUser sortFriend) {
        HashMap<String, String> params = new HashMap<String, String>();
        params.put("access_token", coreManager.getSelfStatus().accessToken);
        params.put("toUserId", sortFriend.getUserId());
        DialogHelper.showDefaulteMessageProgressDialog(this);
        HttpUtils.get().url(coreManager.getConfig().FRIENDS_BLACKLIST_DELETE)
                .params(params)
                .build()
                .execute(new BaseCallback<Void>(Void.class) {

                    @Override
                    public void onResponse(ObjectResult<Void> result) {
                        DialogHelper.dismissProgressDialog();
                        ToastUtil.showToast(BlackActivity.this, "移出黑名单成功");

                        NewFriendMessage message = NewFriendMessage.createWillSendMessage(
                                coreManager.getSelf(), XmppMessage.TYPE_REFUSED, null, sortFriend.getUserId(),sortFriend.getNickname(),sortFriend.getCompanyId());
                        coreManager.sendNewFriendMessage(sortFriend.getUserId(), message);// 移除黑名单
                        // TODO: 2019/7/23 被关注
                        FriendDao.getInstance().updateFriendStatus(mLoginUserId, sortFriend.getUserId(), Friend.STATUS_UNKNOW);

                        ChatMessage removeChatMessage = new ChatMessage();
                        removeChatMessage.setContent("你把" + sortFriend.getNickname() + "移出黑名单");
                        removeChatMessage.setTimeSend(TimeUtils.sk_time_current_time());
                        FriendDao.getInstance().updateLastChatMessage(mLoginUserId, Friend.ID_NEW_FRIEND_MESSAGE, removeChatMessage);
                        NewFriendDao.getInstance().createOrUpdateNewFriend(message);
                        NewFriendDao.getInstance().changeNewFriendState(message.getUserId(), Friend.STATUS_29);
                        ListenerManager.getInstance().notifyNewFriend(mLoginUserId, message, true);

                        CardcastUiUpdateUtil.broadcastUpdateUi(mContext);

                        mSortFriends.remove(sortFriend);
                        mAdapter.notifyDataSetChanged();

                        CardcastUiUpdateUtil.broadcastUpdateUi(BlackActivity.this);
                        MsgBroadcast.broadcastMsgUiUpdate(BlackActivity.this);
                    }

                    @Override
                    public void onError(Call call, Exception e) {
                        DialogHelper.dismissProgressDialog();
                        ToastUtil.showErrorNet(BlackActivity.this);
                    }
                });
    }
}
